<?php
// 课室添加页面 - 完整增强版课室管理功能
// 文件：/workspace/add_room.php

// 启用错误显示用于调试
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 启动会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户登录
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// 数据库连接
require_once 'database.php';

// 独立的权限验证函数 - 避免冲突
function checkUserPermission($user_id, $conn) {
    try {
        $stmt = $conn->prepare("SELECT role FROM user_roles WHERE user_id = ?");
        if (!$stmt) {
            return false;
        }

        $stmt->bind_param("s", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();

        $has_permission = false;
        while ($row = $result->fetch_assoc()) {
            if ($row['role'] === '考试项目管理员') {
                $has_permission = true;
                break;
            }
        }

        $stmt->close();
        return $has_permission;
    } catch (Exception $e) {
        error_log("权限检查失败: " . $e->getMessage());
        return false;
    }
}

// 辅助函数：从楼栋文本中提取数字
function extractBuildingNumber($building_text) {
    if (!$building_text) return null;
    preg_match('/(\d+)/', $building_text, $matches);
    return isset($matches[1]) ? intval($matches[1]) : null;
}

// 辅助函数：从楼层文本中提取数字
function extractFloorNumber($floor_text) {
    if (!$floor_text) return null;
    if (strpos($floor_text, '地下一楼') !== false) return -1;
    preg_match('/(\d+)/', $floor_text, $matches);
    return isset($matches[1]) ? intval($matches[1]) : null;
}

// 验证用户权限
$current_user_id = $_SESSION['user_id'];
if (!checkUserPermission($current_user_id, $conn)) {
    $_SESSION['error_message'] = "您没有权限访问此页面。";
    header("Location: user_home.php");
    exit();
}

// 处理POST请求
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $room_type = $_POST['room_type'] ?? '';
        $building = $_POST['building'] ?? '';
        $floor = $_POST['floor'] ?? '';
        $sub_building = $_POST['sub_building'] ?? '';
        $floor_number = $_POST['floor_number'] ?? '';

        // 新增管理字段 - 所有课室类型都需要
        $administrator_name = $_POST['administrator_name'] ?? '待填写';
        $purpose = $_POST['purpose'] ?? '考场';
        $ownership = $_POST['ownership'] ?? '华材';

        // 学生课室专用字段
        $student_sub_building = '';
        if ($room_type === '学生课室') {
            $student_sub_building = $_POST['student_sub_building'] ?? '主楼';
        }

        // 验证必填字段
        if (empty($room_type) || empty($building) || empty($floor) || empty($floor_number)) {
            throw new Exception("请填写所有必填字段。");
        }

        // 根据规则生成课室号
        $room_number = '';

        if ($room_type === '学生课室') {
            // 学生课室编号规则：楼栋号+楼层号+楼层序号
            $building_num = str_replace(['号楼', '楼'], '', $building);
            $floor_num = str_replace(['楼', '层'], '', $floor);
            $room_number = $building_num . $floor_num . $floor_number . '室';
        } elseif ($room_type === '实训室') {
            if (strpos($building, '5号楼') !== false) {
                // 5号楼编号规则：楼栋号+楼层号+楼层序号
                $room_number = '55' . $floor_number . '室';
            } elseif (strpos($building, '6号楼') !== false) {
                // 6号楼编号规则：楼栋号+楼层号+楼层序号
                $floor_num = str_replace(['楼', '层'], '', $floor);
                $room_number = '6' . $floor_num . $floor_number . '室';
            } elseif (strpos($building, '7号楼') !== false) {
                // 7号楼编号规则：楼栋号+楼层序号
                $room_number = '7-' . str_pad($floor_number, 4, '0', STR_PAD_LEFT) . '室';
            } elseif (strpos($building, '8号楼') !== false) {
                // 8号楼编号规则：楼栋号+楼栋子编号-楼层号+楼层序号
                $floor_num = str_replace(['楼', '层'], '', $floor);
                $room_number = '8' . $sub_building . '-' . $floor_num . str_pad($floor_number, 2, '0', STR_PAD_LEFT) . '室';
            }
        } elseif ($room_type === '电脑机房') {
            if (strpos($building, '4号楼') !== false) {
                // 4号楼编号规则：楼栋号+楼层号+楼层序号
                $room_number = '45' . $floor_number . '室';
            } elseif (strpos($building, '5号楼') !== false) {
                // 5号楼编号规则：按照4号楼5楼的规律
                $room_number = '54' . $floor_number . '室';
            } elseif (strpos($building, '6号楼') !== false) {
                // 6号楼编号规则：楼栋号+楼层号+楼层序号
                $floor_num = str_replace(['楼', '层'], '', $floor);
                $room_number = '6' . $floor_num . $floor_number . '室';
            } elseif (strpos($building, '8号楼') !== false) {
                // 8号楼编号规则：楼栋号+楼栋子编号-楼层号+楼层序号
                $floor_num = str_replace(['楼', '层'], '', $floor);
                $room_number = '8' . $sub_building . '-' . $floor_num . str_pad($floor_number, 2, '0', STR_PAD_LEFT) . '室';
            }
        }

        if (empty($room_number)) {
            throw new Exception("无法生成课室号，请检查输入信息。");
        }

        // 检查课室号是否已存在
        $check_stmt = $conn->prepare("SELECT id FROM examination_rooms WHERE room_number = ?");
        if (!$check_stmt) {
            throw new Exception("数据库查询准备失败: " . $conn->error);
        }

        $check_stmt->bind_param("s", $room_number);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();

        if ($check_result->num_rows > 0) {
            throw new Exception("课室号 {$room_number} 已存在，请检查输入信息。");
        }
        $check_stmt->close();

        // 提取数字格式的楼栋和楼层（用于rooms_display.php兼容）
        $building_number = extractBuildingNumber($building);
        $floor_number_int = extractFloorNumber($floor);

        // 更新容量默认值
        $capacity = 30; // 默认值
        if ($room_type === '学生课室') {
            $capacity = 30; // 修改为30
        } elseif ($room_type === '实训室') {
            $capacity = 30; // 保持30
        } elseif ($room_type === '电脑机房') {
            $capacity = 50; // 修改为50
        }

        // 生成详细地址
        $address = $building . $floor . $room_number;

        // 确定最终的sub_building值（学生课室使用student_sub_building，其他使用sub_building）
        $final_sub_building = '';
        if ($room_type === '学生课室') {
            $final_sub_building = $student_sub_building;
        } else {
            $final_sub_building = $sub_building;
        }

        // 插入课室信息 - 包含所有新增字段
        $insert_stmt = $conn->prepare("
            INSERT INTO examination_rooms 
            (room_number, room_type, capacity, building, floor, sub_building, building_number, floor_number, 
             administrator_name, address, purpose, ownership, created_by, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");

        if (!$insert_stmt) {
            throw new Exception("数据库插入准备失败: " . $conn->error);
        }

        $insert_stmt->bind_param("ssisssiisssss",
            $room_number,
            $room_type,
            $capacity,
            $building,
            $floor,
            $final_sub_building,
            $building_number,
            $floor_number_int,
            $administrator_name,
            $address,
            $purpose,
            $ownership,
            $current_user_id
        );

        if ($insert_stmt->execute()) {
            $success_message = "课室 {$room_number} 添加成功！管理员：{$administrator_name}，用途：{$purpose}，归属：{$ownership}";
        } else {
            throw new Exception("添加课室失败：" . $insert_stmt->error);
        }
        $insert_stmt->close();

    } catch (Exception $e) {
        error_log("添加课室错误: " . $e->getMessage());
        $error_message = $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加课室 - 考务管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="css/unified-style.css">
    <style>
        .room-type-btn {
            margin: 10px;
            padding: 15px 25px;
            font-size: 16px;
            border-radius: 8px;
            transition: all 0.3s ease;
            background-color: white;
            color: #0d6efd;
            border: 1px solid #0d6efd;
        }

        .room-type-btn.active {
            background-color: #0d6efd;
            border-color: #0d6efd;
            color: white;
            transform: scale(1.05);
        }

        .form-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            border-left: 4px solid #0d6efd;
        }

        .building-option, .radio-option {
            margin: 5px;
            padding: 8px 15px;
            font-size: 14px;
            border-radius: 5px;
            background-color: white;
            color: #0d6efd;
            border: 1px solid #0d6efd;
            transition: all 0.3s ease;
        }

        .building-option.active, .radio-option.active {
            background-color: #0d6efd;
            border-color: #0d6efd;
            color: white;
        }

        .hidden {
            display: none;
        }

        .room-preview {
            background: #e3f2fd;
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
            border: 2px solid #2196f3;
        }

        .room-preview h5 {
            color: #1976d2;
            margin-bottom: 10px;
        }

        .preview-number {
            font-size: 24px;
            font-weight: bold;
            color: #0d47a1;
        }

        .enhancement-notice {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            color: #155724;
        }

        .enhancement-notice .badge {
            background: #28a745;
            color: white;
            margin-right: 5px;
        }

        .submit-section {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 30px;
            border-radius: 12px;
            margin: 30px 0;
            border: 2px solid #dee2e6;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        .submit-section .btn {
            padding: 12px 30px;
            font-size: 16px;
            font-weight: 600;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .submit-section .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.15);
        }
    </style>
</head>
<body>
<?php
// 安全包含导航栏
try {
    include_once 'common/navigation.php';
} catch (Exception $e) {
    // 如果导航栏包含失败，显示简单的头部
    echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">';
    echo '<div class="container-fluid">';
    echo '<a class="navbar-brand" href="user_home.php">🎓 考务管理系统</a>';
    echo '<a class="nav-link text-white" href="user_home.php">返回首页</a>';
    echo '</div>';
    echo '</nav>';
}
?>

<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="card shadow">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0"><i class="fas fa-plus-circle"></i> 添加课室 - 8号楼增强版</h4>
                </div>
                <div class="card-body">

                    <!-- 功能增强通知 -->
                    <div class="enhancement-notice">
                        <h6><i class="fas fa-star"></i> 功能增强通知</h6>
                        <p class="mb-0">
                            <span class="badge">ENHANCED</span>
                            8号楼电脑机房现已支持完整楼层：4楼、5楼、6楼、7楼、8楼、9楼、10楼。所有课室类型均包含完整管理功能。
                        </p>
                    </div>

                    <?php if ($success_message): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error_message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <form method="POST" id="addRoomForm">
                        <!-- 步骤1：选择考场类型 -->
                        <div class="form-section">
                            <h5><i class="fas fa-list-alt"></i> 步骤1：选择考场类型</h5>
                            <div class="text-center">
                                <button type="button" class="btn room-type-btn" data-type="学生课室">
                                    <i class="fas fa-chalkboard-teacher"></i><br>学生课室<br><small>容量: 30人</small>
                                </button>
                                <button type="button" class="btn room-type-btn" data-type="实训室">
                                    <i class="fas fa-tools"></i><br>实训室<br><small>容量: 30人</small>
                                </button>
                                <button type="button" class="btn room-type-btn" data-type="电脑机房">
                                    <i class="fas fa-desktop"></i><br>电脑机房<br><small>容量: 50人</small>
                                </button>
                            </div>
                            <input type="hidden" name="room_type" id="room_type" required>
                        </div>

                        <!-- 步骤2：选择楼栋和楼层 -->
                        <div class="form-section hidden" id="buildingSection">
                            <h5><i class="fas fa-building"></i> 步骤2：选择楼栋和楼层</h5>
                            <div id="buildingOptions"></div>
                            <input type="hidden" name="building" id="building" required>
                            <input type="hidden" name="floor" id="floor" required>
                        </div>

                        <!-- 步骤3：楼栋子编号（8号楼专用） -->
                        <div class="form-section hidden" id="subBuildingSection">
                            <h5><i class="fas fa-tags"></i> 步骤3：楼栋子编号</h5>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn building-option" data-sub="A">A座</button>
                                <button type="button" class="btn building-option" data-sub="B">B座</button>
                            </div>
                            <input type="hidden" name="sub_building" id="sub_building">
                        </div>

                        <!-- 步骤4：学生课室楼栋子编号（学生课室专用） -->
                        <div class="form-section hidden" id="studentSubBuildingSection">
                            <h5><i class="fas fa-home"></i> 步骤4：楼栋子编号（学生课室）</h5>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn radio-option active" data-value="主楼">主楼</button>
                                <button type="button" class="btn radio-option" data-value="辅楼">辅楼</button>
                            </div>
                            <input type="hidden" name="student_sub_building" id="student_sub_building" value="主楼">
                        </div>

                        <!-- 步骤5：楼层序号 -->
                        <div class="form-section hidden" id="floorNumberSection">
                            <h5><i class="fas fa-sort-numeric-up"></i> 步骤5：楼层序号</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <label for="floor_number" class="form-label">楼层序号 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" name="floor_number" id="floor_number" min="1" max="99" required>
                                    <div class="form-text">请输入该楼层的课室序号（如第1个课室输入1）</div>
                                </div>
                            </div>
                        </div>

                        <!-- 步骤6：管理员信息（所有课室类型） -->
                        <div class="form-section hidden" id="administratorSection">
                            <h5><i class="fas fa-user-tie"></i> 步骤6：管理员信息（选填）</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <label for="administrator_name" class="form-label">班主任姓名/课室管理员姓名</label>
                                    <input type="text" class="form-control" name="administrator_name" id="administrator_name" value="待填写">
                                    <div class="form-text">可修改，默认为"待填写"</div>
                                </div>
                            </div>
                        </div>

                        <!-- 步骤7：课室用途（所有课室类型） -->
                        <div class="form-section hidden" id="purposeSection">
                            <h5><i class="fas fa-clipboard-list"></i> 步骤7：课室用途（选填）</h5>
                            <div class="row">
                                <div class="col-12">
                                    <button type="button" class="btn radio-option active" data-value="考场">考场</button>
                                    <button type="button" class="btn radio-option" data-value="备用考场">备用考场</button>
                                    <button type="button" class="btn radio-option" data-value="考点办公室">考点办公室</button>
                                    <button type="button" class="btn radio-option" data-value="接待室">接待室</button>
                                    <button type="button" class="btn radio-option" data-value="广播室">广播室</button>
                                    <button type="button" class="btn radio-option" data-value="医疗室">医疗室</button>
                                    <button type="button" class="btn radio-option" data-value="教师办公室">教师办公室</button>
                                    <button type="button" class="btn radio-option" data-value="空白">空白</button>
                                </div>
                            </div>
                            <input type="hidden" name="purpose" id="purpose" value="考场">
                        </div>

                        <!-- 步骤8：归属权（所有课室类型） -->
                        <div class="form-section hidden" id="ownershipSection">
                            <h5><i class="fas fa-certificate"></i> 步骤8：课室归属权（选填）</h5>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn radio-option active" data-value="华材">华材</button>
                                <button type="button" class="btn radio-option" data-value="技工">技工</button>
                            </div>
                            <input type="hidden" name="ownership" id="ownership" value="华材">
                        </div>

                        <!-- 课室号预览 -->
                        <div class="room-preview hidden" id="roomPreview">
                            <h5><i class="fas fa-eye"></i> 课室信息预览</h5>
                            <div class="preview-number" id="previewNumber">-</div>
                            <div class="mt-2">
                                <small class="text-muted d-block">管理员：<span id="previewAdmin">待填写</span></small>
                                <small class="text-muted d-block">用途：<span id="previewPurpose">考场</span></small>
                                <small class="text-muted d-block">归属：<span id="previewOwnership">华材</span></small>
                            </div>
                        </div>

                        <!-- 提交按钮 -->
                        <div class="submit-section text-center">
                            <button type="submit" class="btn btn-success btn-lg me-3" id="submitBtn" disabled>
                                <i class="fas fa-plus-circle"></i> 添加课室
                            </button>
                            <a href="rooms_display.php" class="btn btn-warning btn-lg">
                                <i class="fas fa-list"></i> 查看课室列表
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 课室配置数据
    const roomConfig = {
        '学生课室': {
            buildings: [
                {name: '4号楼', floors: ['6楼', '4楼', '3楼', '2楼']},
                {name: '3号楼', floors: ['6楼', '5楼', '4楼', '3楼', '2楼', '1楼']},
                {name: '2号楼', floors: ['6楼', '5楼', '4楼', '3楼', '2楼', '1楼']},
                {name: '1号楼', floors: ['5楼', '4楼', '3楼', '2楼', '1楼']}
            ],
            needSubBuilding: false,
            needStudentSubBuilding: true
        },
        '实训室': {
            buildings: [
                {name: '5号楼', floors: ['5楼']},
                {name: '6号楼', floors: ['6楼', '5楼', '4楼', '3楼', '2楼', '1楼']},
                {name: '7号楼', floors: ['地下一楼']},
                {name: '8号楼', floors: ['8楼', '4楼', '3楼', '2楼', '1楼']}
            ],
            needSubBuilding: function(building) {
                return building === '8号楼';
            },
            needStudentSubBuilding: false
        },
        '电脑机房': {
            buildings: [
                {name: '4号楼', floors: ['5楼']},
                {name: '5号楼', floors: ['4楼']},
                {name: '6号楼', floors: ['5楼', '3楼', '2楼']},
                {name: '8号楼', floors: ['10楼', '9楼', '8楼', '7楼', '6楼', '5楼', '4楼']}
            ],
            needSubBuilding: function(building) {
                return building === '8号楼';
            },
            needStudentSubBuilding: false
        }
    };

    let selectedType = '';
    let selectedBuilding = '';
    let selectedFloor = '';
    let selectedSubBuilding = '';

    // 选择考场类型
    document.querySelectorAll('.room-type-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.room-type-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            selectedType = this.dataset.type;
            document.getElementById('room_type').value = selectedType;

            showBuildingOptions(selectedType);
            document.getElementById('buildingSection').classList.remove('hidden');
            hideSubsequentSections();
        });
    });

    // 显示楼栋选项
    function showBuildingOptions(roomType) {
        const config = roomConfig[roomType];
        const container = document.getElementById('buildingOptions');
        container.innerHTML = '';

        config.buildings.forEach(building => {
            const buildingDiv = document.createElement('div');
            buildingDiv.className = 'mb-3';

            const buildingTitle = document.createElement('h6');
            buildingTitle.textContent = building.name;
            buildingTitle.className = 'mb-2';
            buildingDiv.appendChild(buildingTitle);

            const floorGroup = document.createElement('div');
            floorGroup.className = 'btn-group-vertical d-inline-block me-3';

            building.floors.forEach(floor => {
                const floorBtn = document.createElement('button');
                floorBtn.type = 'button';
                floorBtn.className = 'btn building-option';
                floorBtn.textContent = floor;
                floorBtn.dataset.building = building.name;
                floorBtn.dataset.floor = floor;

                floorBtn.addEventListener('click', function() {
                    document.querySelectorAll('#buildingOptions .building-option').forEach(b => b.classList.remove('active'));
                    this.classList.add('active');

                    selectedBuilding = this.dataset.building;
                    selectedFloor = this.dataset.floor;
                    document.getElementById('building').value = selectedBuilding;
                    document.getElementById('floor').value = selectedFloor;

                    // 检查是否需要8号楼子编号
                    const needSub = typeof config.needSubBuilding === 'function'
                        ? config.needSubBuilding(selectedBuilding)
                        : config.needSubBuilding;

                    if (needSub) {
                        document.getElementById('subBuildingSection').classList.remove('hidden');
                    } else {
                        document.getElementById('subBuildingSection').classList.add('hidden');
                        selectedSubBuilding = '';
                        document.getElementById('sub_building').value = '';

                        // 检查是否需要学生课室子编号
                        if (config.needStudentSubBuilding) {
                            document.getElementById('studentSubBuildingSection').classList.remove('hidden');
                        } else {
                            document.getElementById('studentSubBuildingSection').classList.add('hidden');
                            showFloorNumberSection();
                        }
                    }
                });

                floorGroup.appendChild(floorBtn);
            });

            buildingDiv.appendChild(floorGroup);
            container.appendChild(buildingDiv);
        });
    }

    // 选择8号楼子编号
    document.querySelectorAll('#subBuildingSection .building-option').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('#subBuildingSection .building-option').forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            selectedSubBuilding = this.dataset.sub;
            document.getElementById('sub_building').value = selectedSubBuilding;

            showFloorNumberSection();
        });
    });

    // 选择学生课室子编号
    document.querySelectorAll('#studentSubBuildingSection .radio-option').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('#studentSubBuildingSection .radio-option').forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            document.getElementById('student_sub_building').value = this.dataset.value;
            showFloorNumberSection();
        });
    });

    // 选择课室用途
    document.querySelectorAll('#purposeSection .radio-option').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('#purposeSection .radio-option').forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            document.getElementById('purpose').value = this.dataset.value;
            updatePreview();
        });
    });

    // 选择课室归属权
    document.querySelectorAll('#ownershipSection .radio-option').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('#ownershipSection .radio-option').forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            document.getElementById('ownership').value = this.dataset.value;
            updatePreview();
        });
    });

    // 显示楼层序号输入
    function showFloorNumberSection() {
        document.getElementById('floorNumberSection').classList.remove('hidden');
        document.getElementById('administratorSection').classList.remove('hidden');
        document.getElementById('purposeSection').classList.remove('hidden');
        document.getElementById('ownershipSection').classList.remove('hidden');
        document.getElementById('roomPreview').classList.remove('hidden');

        // 监听输入事件
        const floorNumberInput = document.getElementById('floor_number');
        const adminInput = document.getElementById('administrator_name');

        floorNumberInput.addEventListener('input', updatePreview);
        adminInput.addEventListener('input', updatePreview);

        updatePreview();
    }

    // 更新预览
    function updatePreview() {
        const floorNumber = document.getElementById('floor_number').value;
        const adminName = document.getElementById('administrator_name').value || '待填写';
        const purpose = document.getElementById('purpose').value;
        const ownership = document.getElementById('ownership').value;

        if (!floorNumber || !selectedType || !selectedBuilding || !selectedFloor) {
            document.getElementById('previewNumber').textContent = '-';
            document.getElementById('submitBtn').disabled = true;
            return;
        }

        let roomNumber = generateRoomNumber(selectedType, selectedBuilding, selectedFloor, selectedSubBuilding, floorNumber);
        document.getElementById('previewNumber').textContent = roomNumber;
        document.getElementById('previewAdmin').textContent = adminName;
        document.getElementById('previewPurpose').textContent = purpose;
        document.getElementById('previewOwnership').textContent = ownership;
        document.getElementById('submitBtn').disabled = false;
    }

    // 生成课室号
    function generateRoomNumber(type, building, floor, subBuilding, floorNumber) {
        if (type === '学生课室') {
            const buildingNum = building.replace(/[号楼]/g, '');
            const floorNum = floor.replace(/[楼层]/g, '');
            return buildingNum + floorNum + floorNumber + '室';
        } else if (type === '实训室') {
            if (building === '5号楼') {
                return '55' + floorNumber + '室';
            } else if (building === '6号楼') {
                const floorNum = floor.replace(/[楼层]/g, '');
                return '6' + floorNum + floorNumber + '室';
            } else if (building === '7号楼') {
                return '7-' + floorNumber.padStart(4, '0') + '室';
            } else if (building === '8号楼') {
                const floorNum = floor.replace(/[楼层]/g, '');
                return '8' + subBuilding + '-' + floorNum + floorNumber.padStart(2, '0') + '室';
            }
        } else if (type === '电脑机房') {
            if (building === '4号楼') {
                return '45' + floorNumber + '室';
            } else if (building === '5号楼') {
                // 5号楼4楼按照4号楼5楼的规律
                return '54' + floorNumber + '室';
            } else if (building === '6号楼') {
                const floorNum = floor.replace(/[楼层]/g, '');
                return '6' + floorNum + floorNumber + '室';
            } else if (building === '8号楼') {
                const floorNum = floor.replace(/[楼层]/g, '');
                return '8' + subBuilding + '-' + floorNum + floorNumber.padStart(2, '0') + '室';
            }
        }
        return '-';
    }

    // 隐藏后续步骤
    function hideSubsequentSections() {
        document.getElementById('subBuildingSection').classList.add('hidden');
        document.getElementById('studentSubBuildingSection').classList.add('hidden');
        document.getElementById('floorNumberSection').classList.add('hidden');
        document.getElementById('administratorSection').classList.add('hidden');
        document.getElementById('purposeSection').classList.add('hidden');
        document.getElementById('ownershipSection').classList.add('hidden');
        document.getElementById('roomPreview').classList.add('hidden');
        document.getElementById('submitBtn').disabled = true;

        // 清除选择
        selectedBuilding = '';
        selectedFloor = '';
        selectedSubBuilding = '';
        document.getElementById('building').value = '';
        document.getElementById('floor').value = '';
        document.getElementById('sub_building').value = '';
        document.getElementById('floor_number').value = '';
    }
</script>
</body>
</html>